import { GAME_CONFIG } from './config.js';
import { Player } from './player.js';
import { PowerupSystem } from './powerup.js';
import { ObstacleSystem } from './obstacle.js';
import { AudioManager } from './audio.js';
import { LevelManager } from './level.js';

export class Game {
    constructor() {
        this.totalDistance = 0;
        this.highScore = 0;
        this.isPaused = false;
        this.isGameStarted = false;
        this.audioManager = new AudioManager();
        this.levelManager = new LevelManager();

        // 新手引导相关属性
        this.tutorialActive = false;
        this.currentTutorialStep = 0;
        this.tutorialSteps = [
            { text: "欢迎来到3D跑酷！点击'下一步'了解基本操作。", highlight: null },
            { text: "按 '↑'键 或 点击屏幕上方区域 进行重力反转，在地面和天花板之间切换。", highlight: null }, // 稍后可以高亮整个游戏区域或者特定按钮
            { text: "按 '←' 和 '→' 键 或 滑动屏幕左右 来控制角色左右移动。", highlight: null },
            { text: "按 '空格键' 或 点击屏幕下方区域 进行跳跃，躲避障碍物。", highlight: null },
            { text: "注意观察左上角的分数和关卡。", highlight: "gameStats" }, // 高亮整个 game-stats 区域
            { text: "右上角的按钮可以暂停游戏。", highlight: "pauseButton" },
            { text: "收集道具可以获得特殊效果，例如加速或护盾！", highlight: null }, // 考虑高亮道具图标区域（如果游戏中有的话）
            { text: "现在你已经了解了基本操作，祝你游戏愉快！点击'完成'开始游戏。", highlight: null }
        ];
        
        // 初始化3D场景
        this.initialize();
        
        // 初始化UI事件监听
        this.initializeUIEvents();
        
        // 显示开始菜单
        document.getElementById('startMenu').classList.remove('hidden');
        
        // 开始渲染循环
        this.render();
    }

    initializeUIEvents() {
        // 开始菜单按钮
        document.getElementById('startButton').addEventListener('click', () => this.startGame());
        document.getElementById('settingsButton').addEventListener('click', () => this.showPanel('settingsPanel'));
        document.getElementById('instructionsButton').addEventListener('click', () => this.showPanel('instructionsPanel'));

        // 暂停菜单按钮
        document.getElementById('pauseButton').addEventListener('click', () => this.togglePause());
        document.getElementById('resumeButton').addEventListener('click', () => this.togglePause());
        document.getElementById('restartButton').addEventListener('click', () => this.restartGame());
        document.getElementById('mainMenuButton').addEventListener('click', () => this.returnToMainMenu());
        document.getElementById('pauseSettingsButton').addEventListener('click', () => this.showPanel('settingsPanel'));

        // 游戏结束菜单按钮
        document.getElementById('playAgainButton').addEventListener('click', () => this.restartGame());
        document.getElementById('gameOverMainMenuButton').addEventListener('click', () => this.returnToMainMenu());

        // 设置面板
        document.getElementById('musicVolume').addEventListener('input', (e) => {
            this.audioManager.setMusicVolume(e.target.value / 100);
        });
        document.getElementById('sfxVolume').addEventListener('input', (e) => {
            this.audioManager.setSFXVolume(e.target.value / 100);
        });
        document.getElementById('settingsBackButton').addEventListener('click', () => {
            this.hidePanel('settingsPanel');
            if (this.isPaused) {
                document.getElementById('pauseMenu').classList.remove('hidden');
            } else if (!this.isGameStarted) {
                document.getElementById('startMenu').classList.remove('hidden');
            }
        });

        // 操作说明面板
        document.getElementById('instructionsBackButton').addEventListener('click', () => {
            this.hidePanel('instructionsPanel');
            if (!this.isGameStarted) {
                document.getElementById('startMenu').classList.remove('hidden');
            }
        });

        // 新手引导按钮
        document.getElementById('nextTutorialButton').addEventListener('click', () => this.handleTutorialNext());
        document.getElementById('skipTutorialButton').addEventListener('click', () => this.skipTutorial());
    }

    initialize() {
        // 创建场景
        this.scene = new THREE.Scene();
        
        // 创建摄像机
        this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        this.camera.position.z = 15;
        this.camera.position.y = 5;

        // 创建渲染器
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.scene.background = new THREE.Color(GAME_CONFIG.SCENE_FOG.color);
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(this.renderer.domElement);

        // 初始化游戏系统
        this.player = new Player(this.scene);
        this.obstacleSystem = new ObstacleSystem(this.scene);
        this.powerupSystem = new PowerupSystem(this.scene);

        // 设置游戏状态
        this.gravity = new THREE.Vector3(0, GAME_CONFIG.GRAVITY, 0);
        this.panSpeed = this.player.baseSpeed;

        // 创建游戏环境
        this.createFloor();
        this.createCeiling();
        this.addLights();
        
        // 添加雾效
        this.scene.fog = new THREE.Fog(
            GAME_CONFIG.SCENE_FOG.color,
            GAME_CONFIG.SCENE_FOG.near,
            GAME_CONFIG.SCENE_FOG.far
        );

        // 添加事件监听
        this.setupEventListeners();

        // 初始化关卡UI
        document.getElementById('level').textContent = this.levelManager.currentLevel;
        document.getElementById('theme').textContent = this.levelManager.getCurrentTheme().name;
        
        // 应用初始主题
        const theme = this.levelManager.getCurrentTheme();
        this.scene.background = new THREE.Color(theme.backgroundColor);
        this.scene.fog.color = new THREE.Color(theme.backgroundColor);
        
        // 将相机移动到观赏位置
        this.camera.position.set(15, 5, 15);
        this.camera.lookAt(0, 0, 0);
    }

    createFloor() {
        const geometry = new THREE.BoxGeometry(
            GAME_CONFIG.FLOOR_CONFIG.width,
            GAME_CONFIG.FLOOR_CONFIG.height,
            GAME_CONFIG.FLOOR_CONFIG.depth
        );
        const material = new THREE.MeshLambertMaterial({ color: GAME_CONFIG.FLOOR_CONFIG.color });
        this.floor = new THREE.Mesh(geometry, material);
        this.scene.add(this.floor);
    }

    createCeiling() {
        const geometry = new THREE.BoxGeometry(
            GAME_CONFIG.FLOOR_CONFIG.width,
            GAME_CONFIG.FLOOR_CONFIG.height,
            GAME_CONFIG.FLOOR_CONFIG.depth
        );
        const material = new THREE.MeshLambertMaterial({ color: GAME_CONFIG.FLOOR_CONFIG.color });
        this.ceiling = new THREE.Mesh(geometry, material);
        this.ceiling.position.y = 15;
        this.scene.add(this.ceiling);
    }

    addLights() {
        // 添加半球光源
        const hemiLight = new THREE.HemisphereLight(0xffffbb, 0x080820, 1);
        this.scene.add(hemiLight);

        // 添加点光源
        this.pointLight = new THREE.PointLight(0xff0000, 1, 100);
        this.pointLight.position.set(10, 7.5, this.player.pos.z);
        this.scene.add(this.pointLight);
    }

    startGame() {
        // 检查是否已经完成过新手引导
        const tutorialCompleted = localStorage.getItem('tutorialCompleted');
        if (!tutorialCompleted) {
            this.startTutorial();
        } else {
            this.startGameImmediately();
        }
    }

    // 新的直接开始游戏的方法
    startGameImmediately() {
        this.isGameStarted = true;
        document.getElementById('startMenu').classList.add('hidden');
        document.getElementById('gameUI').classList.remove('hidden');
        
        // 重置相机位置到游戏视角
        this.camera.position.set(0, 2, 10);
        this.camera.rotation.set(0, 0, 0);
        this.camera.lookAt(0, 2, 0);
        
        // 初始化并播放当前主题的背景音乐
        const currentTheme = this.levelManager.getCurrentTheme();
        this.audioManager.loadBackgroundMusic(this.levelManager.currentTheme);
        
        // 重置游戏状态
        this.reset();
    }

    togglePause() {
        this.isPaused = !this.isPaused;
        if (this.isPaused) {
            document.getElementById('pauseMenu').classList.remove('hidden');
            this.audioManager.pauseAll();
        } else {
            document.getElementById('pauseMenu').classList.add('hidden');
            this.audioManager.resumeAll();
        }
    }

    showPanel(panelId) {
        // 隐藏其他所有面板
        ['startMenu', 'pauseMenu', 'settingsPanel', 'instructionsPanel', 'gameOverMenu'].forEach(id => {
            document.getElementById(id).classList.add('hidden');
        });
        // 显示目标面板
        document.getElementById(panelId).classList.remove('hidden');
    }

    hidePanel(panelId) {
        document.getElementById(panelId).classList.add('hidden');
    }

    returnToMainMenu() {
        this.isGameStarted = false;
        this.isPaused = false;
        this.audioManager.stopBackgroundMusic();
        
        // 隐藏所有游戏相关UI
        ['gameUI', 'pauseMenu', 'gameOverMenu'].forEach(id => {
            document.getElementById(id).classList.add('hidden');
        });
        
        // 显示开始菜单
        document.getElementById('startMenu').classList.remove('hidden');
        
        // 重置游戏状态
        if (this.scene) {
            this.reset();
        }
    }

    restartGame() {
        this.isPaused = false;
        document.getElementById('pauseMenu').classList.add('hidden');
        document.getElementById('gameOverMenu').classList.add('hidden');
        
        this.reset();
        this.audioManager.playBackgroundMusic();
    }

    setupEventListeners() {
        // 窗口大小改变事件
        window.addEventListener("resize", () => {
            this.renderer.setSize(window.innerWidth, window.innerHeight);
            this.camera.aspect = window.innerWidth / window.innerHeight;
            this.camera.updateProjectionMatrix();
        });

        // 键盘控制
        document.addEventListener('keyup', (e) => {
            if (!this.isGameStarted || this.isPaused) return;

            // 上箭头键 - 重力反转
            if (e.code === "ArrowUp") {
                this.gravity.y *= -1;
                this.player.vel.y = 0;
                this.tl = new TimelineMax();
                if (this.camera.rotation.z == 0) {
                    this.tl.to(this.camera.rotation, .2, { z: Math.PI });
                } else {
                    this.tl.to(this.camera.rotation, .2, { z: Math.PI * 2 });
                    this.tl.to(this.camera.rotation, 0, { z: 0 });
                }
                this.audioManager.playSound('jump');
            }
            
            const isInverted = this.camera.rotation.z !== 0;
            
            // 空格键 - 跳跃
            if (e.code === "Space") {
                this.player.jump(isInverted);
                this.audioManager.playSound('jump');
            }
            
            // 左右箭头 - 移动
            if (e.code === "ArrowLeft" || e.code === "ArrowRight") {
                const direction = e.code === "ArrowLeft" ? -1 : 1;
                this.player.move(direction, isInverted);
            }

            // ESC键 - 暂停
            if (e.code === "Escape") {
                this.togglePause();
            }
        });
    }

    update() {
        if (!this.isGameStarted || this.isPaused) return;

        // 更新玩家
        this.player.update(this.gravity);
        this.player.checkCollision(this.player.pos.y, this.camera.rotation.z);

        // 更新障碍物和检测碰撞
        this.obstacleSystem.update(this.panSpeed);
        const dead = this.obstacleSystem.checkCollision(
            this.player,
            this.powerupSystem.powerupEffects.shield
        );

        if (dead) {
            this.handleDeath();
        } else {
            // 更新道具系统
            this.panSpeed = this.powerupSystem.update(this.player, this.panSpeed);
            
            // 获取当前关卡配置
            const config = this.levelManager.getLevelConfig();
            
            // 持续增加游戏速度，但基于当前关卡的速度倍率
            this.panSpeed += 0.0001 * config.obstacleSpeed;

            // 更新总距离
            this.totalDistance += this.panSpeed;
        }

        // 更新光源和相机位置
        this.pointLight.position.set(10, 7.5, this.player.pos.z);
        this.camera.position.set(this.player.pos.x, this.player.pos.y, this.player.pos.z);

        // 更新得分显示
        this.updateScore();
    }

    handleDeath() {
        this.player.hit = true;
        this.panSpeed = this.player.baseSpeed - 0.001;
        
        // 播放碰撞音效
        this.audioManager.playSound('collision');
        
        // 获取当前显示分数
        const currentScore = this.levelManager.getDisplayScore();
        
        // 更新最高分
        if (currentScore > this.highScore) {
            this.highScore = currentScore;
        }
        
        // 更新游戏结束界面分数
        document.getElementById('finalScore').textContent = currentScore;
        document.getElementById('highScore').textContent = Math.floor(this.highScore);
        
        // 显示游戏结束界面
        this.showPanel('gameOverMenu');
        
        // 停止背景音乐
        this.audioManager.stopBackgroundMusic();
        
        // 重置游戏状态
        this.reset();

        // 暂停游戏
        this.isPaused = true;
    }

    updateScore() {
        // 更新分数并检查是否需要升级
        if (this.levelManager.updateScore(1)) {
            // 播放升级音效
            this.audioManager.playSound('levelUp');
            
            // 获取新主题
            const theme = this.levelManager.getCurrentTheme();
            
            // 延迟切换背景音乐，让升级音效先播放
            setTimeout(() => {
                this.audioManager.changeTheme(this.levelManager.currentTheme);
            }, 1000);
            
            // 更新游戏参数
            const config = this.levelManager.getLevelConfig();
            // 保持当前速度并应用新的倍率
            this.panSpeed *= 2; // 速度翻倍
            this.obstacleSystem.updateSpeed(config.obstacleSpeed);
            this.obstacleSystem.updateFrequency(config.obstacleFrequency);
            this.obstacleSystem.setObstacleType(config.obstacleType);
            
            // 更新UI显示
            document.getElementById('level').textContent = this.levelManager.currentLevel;
            document.getElementById('theme').textContent = theme.name;
            
            // 更新视觉效果
            this.scene.background = new THREE.Color(theme.backgroundColor);
            this.scene.fog.color = new THREE.Color(theme.backgroundColor);
            this.floor.material.color = new THREE.Color(theme.groundColor);
            this.ceiling.material.color = new THREE.Color(theme.groundColor);
            this.player.mesh.material.color = new THREE.Color(theme.playerColor);
        }

        // 更新分数显示
        document.getElementById('score').textContent = this.levelManager.getDisplayScore();
        
        // 更新进度条（如果存在）
        const progressBar = document.getElementById('levelProgress');
        if (progressBar) {
            progressBar.style.width = `${this.levelManager.getLevelProgress() * 100}%`;
        }
        
        // 更新下一级分数显示（如果存在）
        const nextLevelScore = document.getElementById('nextLevelScore');
        if (nextLevelScore) {
            nextLevelScore.textContent = this.levelManager.getNextLevelScore();
        }
    }

    reset() {
        this.score = 0;
        document.getElementById('score').textContent = '0';
        this.levelManager = new LevelManager();
        document.getElementById('level').textContent = this.levelManager.currentLevel;
        document.getElementById('theme').textContent = this.levelManager.getCurrentTheme().name;
        
        // 重置主题
        const theme = this.levelManager.getCurrentTheme();
        this.scene.background = new THREE.Color(theme.backgroundColor);
        this.scene.fog.color = new THREE.Color(theme.backgroundColor);
        
        this.totalDistance = 0;
        this.panSpeed = this.player.baseSpeed; // 重置为基础速度
        
        // 重置相机位置（如果不是在开始菜单状态）
        if (this.isGameStarted) {
            this.camera.position.set(0, 2, 10);
            this.camera.rotation.set(0, 0, 0);
        }
        
        this.player.reset();
        this.obstacleSystem.reset();
        this.powerupSystem.reset();
    }

    render() {
        requestAnimationFrame(() => this.render());
        
        // 即使在开始菜单，也让场景缓慢移动以产生动态效果
        if (!this.isGameStarted) {
            // 缓慢旋转相机
            this.camera.position.x = Math.sin(Date.now() * 0.001) * 15;
            this.camera.position.z = Math.cos(Date.now() * 0.001) * 15;
            this.camera.position.y = 5 + Math.sin(Date.now() * 0.0005) * 2;
            this.camera.lookAt(0, 0, 0);
            
            // 更新光源位置
            if (this.pointLight) {
                this.pointLight.position.copy(this.camera.position);
            }
        } else {
        this.update();
        }
        
        this.renderer.render(this.scene, this.camera);
    }

    // 新手引导逻辑开始
    startTutorial() {
        this.tutorialActive = true;
        this.currentTutorialStep = 0;
        document.getElementById('startMenu').classList.add('hidden');
        document.getElementById('tutorialOverlay').classList.remove('hidden');
        this.showTutorialStep(this.currentTutorialStep);
        // 标记引导已完成，避免下次再次显示 (可以使用 localStorage)
        localStorage.setItem('tutorialCompleted', 'true');
    }

    showTutorialStep(stepIndex) {
        if (stepIndex >= this.tutorialSteps.length) {
            this.endTutorial();
            return;
        }

        const step = this.tutorialSteps[stepIndex];
        document.getElementById('tutorialText').textContent = step.text;

        // 处理高亮
        this.clearHighlights();
        if (step.highlight) {
            const elementToHighlight = document.getElementById(step.highlight);
            if (elementToHighlight) {
                elementToHighlight.classList.add('tutorial-highlight');
                 // 如果高亮的是游戏统计或暂停按钮，确保游戏UI是可见的
                if (step.highlight === 'gameStats' || step.highlight === 'pauseButton') {
                    document.getElementById('gameUI').classList.remove('hidden');
                }
            }
        }

        const nextButton = document.getElementById('nextTutorialButton');
        if (stepIndex === this.tutorialSteps.length - 1) {
            nextButton.textContent = '完成';
        } else {
            nextButton.textContent = '下一步';
        }
    }

    handleTutorialNext() {
        this.currentTutorialStep++;
        this.showTutorialStep(this.currentTutorialStep);
    }

    endTutorial() {
        this.tutorialActive = false;
        document.getElementById('tutorialOverlay').classList.add('hidden');
        this.clearHighlights();
        // 引导结束后，正式开始游戏
        this.isGameStarted = true; // 确保 isGameStarted 状态正确
        document.getElementById('gameUI').classList.remove('hidden');
        this.camera.position.set(0, 2, 10);
        this.camera.rotation.set(0, 0, 0);
        this.camera.lookAt(0, 2, 0);
        const currentTheme = this.levelManager.getCurrentTheme();
        this.audioManager.loadBackgroundMusic(this.levelManager.currentTheme);
        this.reset(); // 调用 reset 来初始化游戏元素
    }

    skipTutorial() {
        this.tutorialActive = false;
        document.getElementById('tutorialOverlay').classList.add('hidden');
        this.clearHighlights();
        localStorage.setItem('tutorialCompleted', 'true'); // 同样标记为已完成
        this.startGameImmediately(); // 调用直接开始游戏的方法
    }
    
    // 用于清除所有高亮效果
    clearHighlights() {
        const highlightedElements = document.querySelectorAll('.tutorial-highlight');
        highlightedElements.forEach(el => el.classList.remove('tutorial-highlight'));
        // 如果之前为了高亮显示了 gameUI，在不需要时可以考虑隐藏，但这取决于引导流程
        // document.getElementById('gameUI').classList.add('hidden'); 
    }
    // 新手引导逻辑结束
}

// 启动游戏
new Game(); 